<template>
    <el-dialog title="编辑题目详情" :visible.sync="dialogVisible" width="60%" :close-on-click-modal="false" :modal="false"
        :append-to-body="true" class="question-detail-editor">

        <div class="detail-editor-container">
            <!-- 通用字段 -->
            <el-form :model="editForm" label-width="100px" ref="editForm" :rules="formRules">
                <el-form-item label="题目内容" prop="question">
                    <el-input v-model="editForm.question" type="textarea" :rows="3" placeholder="请输入题目内容"
                        maxlength="500" show-word-limit>
                    </el-input>
                </el-form-item>

                <el-form-item label="知识点" prop="point">
                    <el-input v-model="editForm.point" placeholder="请输入相关知识点" maxlength="100" show-word-limit>
                    </el-input>
                </el-form-item>

                <!-- 单选题特有字段 -->
                <template v-if="questionType === 'choice'">
                    <el-form-item label="选项" prop="choose">
                        <div v-for="(choice, index) in (editForm.choose || [])" :key="index" class="choice-input-item">
                            <el-input v-model="editForm.choose[index]"
                                :placeholder="`选项 ${String.fromCharCode(65 + index)}`" class="choice-input">
                                <template slot="prepend">{{ String.fromCharCode(65 + index) }}.</template>
                            </el-input>
                            <el-button v-if="editForm.choose && editForm.choose.length > 2" type="danger"
                                icon="el-icon-delete" size="mini" @click="removeChoice(index)"
                                class="remove-choice-btn">
                            </el-button>
                        </div>
                        <el-button v-if="editForm.choose && editForm.choose.length < 6" type="primary"
                            icon="el-icon-plus" size="mini" @click="addChoice" class="add-choice-btn">
                            添加选项
                        </el-button>
                    </el-form-item>

                    <el-form-item label="正确答案" prop="answer">
                        <el-select v-model="editForm.answer" placeholder="请选择正确答案">
                            <el-option v-for="(choice, index) in (editForm.choose || [])" :key="index" :label="choice"
                                :value="choice">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </template>

                <!-- 判断题特有字段 -->
                <template v-if="questionType === 'TF'">
                    <el-form-item label="正确答案" prop="answer">
                        <el-radio-group v-model="editForm.answer">
                            <el-radio :label="true">正确</el-radio>
                            <el-radio :label="false">错误</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template>

                <!-- 填空题特有字段 -->
                <template v-if="questionType === 'fill'">
                    <el-form-item label="参考答案" prop="answer">
                        <div v-for="(answer, index) in (editForm.answer || [])" :key="index" class="fill-answer-item">
                            <el-input v-model="editForm.answer[index]" :placeholder="`参考答案 ${index + 1}`"
                                class="fill-answer-input">
                            </el-input>
                            <el-button v-if="editForm.answer && editForm.answer.length > 1" type="danger"
                                icon="el-icon-delete" size="mini" @click="removeFillAnswer(index)"
                                class="remove-answer-btn">
                            </el-button>
                        </div>
                        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addFillAnswer"
                            class="add-answer-btn">
                            添加答案
                        </el-button>
                    </el-form-item>
                </template>

                <!-- 简答题特有字段 -->
                <template v-if="questionType === 'answer'">
                    <el-form-item label="参考答案" prop="answer">
                        <el-input v-model="editForm.answer" type="textarea" :rows="4" placeholder="请输入参考答案"
                            maxlength="1000" show-word-limit>
                        </el-input>
                    </el-form-item>
                </template>
            </el-form>
        </div>

        <span slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
    </el-dialog>
</template>

<script>
export default {
    name: 'QuestionDetailEditor',
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        question: {
            type: Object,
            default: () => ({})
        },
        questionType: {
            type: String,
            required: true
        },
        questionIndex: {
            type: Number,
            default: -1
        }
    },
    data() {
        return {
            dialogVisible: false,
            editForm: {
                question: '',
                point: '',
                answer: '',
                choose: []
            },
            formRules: {
                question: [
                    { required: true, message: '请输入题目内容', trigger: 'blur' },
                    { min: 5, message: '题目内容至少5个字符', trigger: 'blur' }
                ],
                point: [
                    { required: true, message: '请输入知识点', trigger: 'blur' }
                ],
                answer: [
                    { required: true, message: '请设置正确答案', trigger: 'change' }
                ]
            }
        }
    },
    watch: {
        visible(newVal) {
            this.dialogVisible = newVal;
            if (newVal && this.question) {
                this.initEditForm();
            }
        },
        dialogVisible(newVal) {
            if (!newVal) {
                this.$emit('update:visible', false);
            }
        }
    },
    methods: {
        // 初始化编辑表单
        initEditForm() {
            // 深拷贝问题数据，如果没有问题数据则使用默认值
            if (this.question && Object.keys(this.question).length > 0) {
                this.editForm = JSON.parse(JSON.stringify(this.question));
            } else {
                // 创建默认的空题目
                this.editForm = {
                    question: '',
                    point: '',
                    answer: this.questionType === 'fill' ? [''] : (this.questionType === 'TF' ? false : ''),
                    choose: this.questionType === 'choice' ? ['A. ', 'B. ', 'C. ', 'D. '] : undefined
                };
            }

            // 确保数据结构正确
            if (this.questionType === 'choice') {
                if (!Array.isArray(this.editForm.choose) || this.editForm.choose.length === 0) {
                    this.editForm.choose = ['A. ', 'B. ', 'C. ', 'D. '];
                }
            }

            if (this.questionType === 'fill') {
                if (!Array.isArray(this.editForm.answer)) {
                    this.editForm.answer = [this.editForm.answer || ''];
                }
            }

            if (this.questionType === 'TF') {
                if (typeof this.editForm.answer !== 'boolean') {
                    this.editForm.answer = false;
                }
            }
        },

        // 添加选择题选项
        addChoice() {
            if (!this.editForm.choose) {
                this.editForm.choose = [];
            }
            if (this.editForm.choose.length < 6) {
                const nextLetter = String.fromCharCode(65 + this.editForm.choose.length);
                this.editForm.choose.push(`${nextLetter}. `);
            }
        },

        // 删除选择题选项
        removeChoice(index) {
            if (!this.editForm.choose || this.editForm.choose.length <= 2) {
                return;
            }
            if (this.editForm.choose.length > 2) {
                // 如果删除的是当前正确答案，清空正确答案
                if (this.editForm.answer === this.editForm.choose[index]) {
                    this.editForm.answer = '';
                }
                this.editForm.choose.splice(index, 1);

                // 重新排列选项标记
                this.editForm.choose.forEach((choice, idx) => {
                    const letter = String.fromCharCode(65 + idx);
                    if (!choice.startsWith(`${letter}.`)) {
                        this.editForm.choose[idx] = `${letter}. ${choice.substring(3)}`;
                    }
                });
            }
        },

        // 添加填空题答案
        addFillAnswer() {
            if (!Array.isArray(this.editForm.answer)) {
                this.editForm.answer = [];
            }
            this.editForm.answer.push('');
        },

        // 删除填空题答案
        removeFillAnswer(index) {
            if (!Array.isArray(this.editForm.answer) || this.editForm.answer.length <= 1) {
                return;
            }
            if (this.editForm.answer.length > 1) {
                this.editForm.answer.splice(index, 1);
            }
        },

        // 保存
        handleSave() {
            this.$refs.editForm.validate((valid) => {
                if (valid) {
                    // 验证选择题特殊逻辑
                    if (this.questionType === 'choice') {
                        if (!this.editForm.choose.every(choice => choice.trim().length > 3)) {
                            this.$message.error('请填写完整的选项内容');
                            return;
                        }
                        if (!this.editForm.answer || !this.editForm.choose.includes(this.editForm.answer)) {
                            this.$message.error('请选择正确的答案选项');
                            return;
                        }
                    }

                    // 验证填空题特殊逻辑
                    if (this.questionType === 'fill') {
                        if (!this.editForm.answer.every(ans => ans.trim().length > 0)) {
                            this.$message.error('请填写完整的参考答案');
                            return;
                        }
                    }

                    this.$emit('save', JSON.parse(JSON.stringify(this.editForm)));
                } else {
                    this.$message.error('请检查表单填写是否完整');
                }
            });
        },

        // 取消
        handleCancel() {
            this.dialogVisible = false;
        }
    }
}
</script>

<style scoped>
/* 确保详情编辑对话框在上层 */
.question-detail-editor :deep(.el-dialog) {
    z-index: 3000 !important;
}

.question-detail-editor :deep(.el-dialog__wrapper) {
    z-index: 3000 !important;
}

.detail-editor-container {
    max-height: 60vh;
    overflow-y: auto;
}

.choice-input-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.choice-input {
    flex: 1;
    margin-right: 8px;
}

.remove-choice-btn {
    flex-shrink: 0;
}

.add-choice-btn {
    margin-top: 8px;
}

.fill-answer-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.fill-answer-input {
    flex: 1;
    margin-right: 8px;
}

.remove-answer-btn {
    flex-shrink: 0;
}

.add-answer-btn {
    margin-top: 8px;
}

/* 滚动条样式 */
.detail-editor-container::-webkit-scrollbar {
    width: 6px;
}

.detail-editor-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.detail-editor-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.detail-editor-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>
